// send-verification-code.js
import nodemailer from 'nodemailer';
import { NextResponse } from 'next/server';
import { verificationDB } from '@/utils/verificationDB'; // 引入共享实例

// 内存缓存（可选，用于优化性能）
const verificationCache = new Map();

// 发送邮件方法
const sendEmailAsync = (transporter, mailOptions) => {
  return new Promise((resolve, reject) => {
    transporter.sendMail(mailOptions, (error, info) => {
      if (error) reject(error);
      else resolve(info);
    });
  });
};

export const POST = async (request) => {
  try {
    // 验证请求格式
    if (!request.headers.get('Content-Type')?.includes('application/json')) {
      return NextResponse.json({
        message: "请求需为 JSON 格式",
        success: false
      }, { status: 400 });
    }

    const { email } = await request.json();
    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      return NextResponse.json({
        message: "请输入有效的邮箱地址",
        success: false
      }, { status: 400 });
    }

    // 生成验证码（6位数字）
    const code = Math.floor(100000 + Math.random() * 900000).toString();
    const expires = Date.now() + 5 * 60 * 1000; // 5分钟有效期

    // 先删除该邮箱的旧验证码（避免重复）
    await verificationDB.remove({ email }, { multi: true });

    // 插入新验证码（并更新缓存）
    const newDoc = await verificationDB.insert({ email, code, expires });
    verificationCache.set(email, newDoc);

    // 配置邮件 transporter（建议抽离为环境变量）
    const transporter = nodemailer.createTransport({
      host: "smtp.qq.com",
      port: 465,
      secure: true,
      auth: {
        user: "1690544550@qq.com",
        pass: "znxogkkkexpbeeaj" // 注意：生产环境使用环境变量存储
      },
      pool: true // 启用连接池
    });

    // 发送邮件
    await sendEmailAsync(transporter, {
      from: "1690544550@qq.com",
      to: email,
      subject: "邮箱验证码",
      text: `您的验证码是：${code}，5分钟内有效。`
    });

    return NextResponse.json({
      message: "验证码发送成功",
      success: true
    });

  } catch (error) {
    console.error("发送验证码失败:", error);
    return NextResponse.json({
      message: "验证码发送失败，请稍后重试",
      success: false
    }, { status: 500 });
  }
};